from bot.enterprise_wechat_gpt.util.llm_agent_aio import *
from bot.enterprise_wechat_gpt.util.merge_conversation_util import *


async def self_utter_generate(deal_conversation_history, user_id='User_abcd'):
    if len(deal_conversation_history) < 3:
        return '无'
    # deal_conversation_history = [d if list(d.keys())[0] == '用户' else {'销售员': list(d.values())[0]} for d in deal_conversation_history]
    conversation_str = '\n###'.join([f"{key}:{value}" for d in deal_conversation_history for key, value in d.items()])
    prompt = f"""请不要忘记，你是专业的、非常懂营销的信贷领域的销售员，你的名字叫京小鑫，你现在在通过微信和用户进行沟通。你主要的任务是在回应并解决用户的问题，然后完成金条和信用卡的销售转化。
###{conversation_str}
###{ASSISTANT}:"""
    chat = LLMAgent(prompt)
    try:
        result = await chat.achat_llm(model_version='wechat_llm', max_new_tokens=350)   # TODO 修改成和master环境一致的 vicune-13b模型
    except Exception as e:
        logging.error(f'获取话术示例超时: {user_id} e:{e}')
        result = '无'
    # result = chat.async_chat_with_openai()
    # for data in result:
    #     logger.info(data)
    if "NETWORK ERROR DUE TO HIGH TRAFFIC" in result:
        logging.warning(f"=====> userId:[{user_id}] 2.3 LLM Self_Model_Result: {result} 转成无<=====")
        result = "无"
    logging.info(f"=====> userId:[{user_id}] 2.3 LLM Self_Model_Result: {result} <=====")
    return result




if __name__ == "__main__":
    role1, role2 = ASSISTANT, USER   #############################TODO 身份替换ASSISTANT
    raw_conversation_history = [
        {role2: '帐户显示43000的剩余额度，需要2万，坐席申请了一张6折券，用户借款失败。'},
        {role1: '有借款需要的话，可以通过企微专属链接借款，以便后期系统复审时您有机会调整额度和利率，具体显示以页面为准。请问您这次需要解决什么财务问题呢？您目前界面还有额度哈？'},
        # {role2: '我分分卡额度咋没额度了'},
        # {role2: '你能给提点么'},
        # {role1: '您的额度问题我记下了哈~小鑫现在带您查看一下提额的名额哈！'},
        # {role2: '好的，提额专区？'}, {role2: '我这里好像有几条'}
    ]
    deal_conversation_history = merge_role_conversation(raw_conversation_history)
    print(len(raw_conversation_history), len(deal_conversation_history))

    loops = asyncio.get_event_loop()
    res_self_utter = loops.run_until_complete(self_utter_generate(deal_conversation_history[-10:]))
    print(res_self_utter)



